<template>
    <div :class="search_border ? 'search search_border' : 'search'">
        <Search style="width: 10px;color: #fff;margin: 0 6px;" />
        <input @compositionend="Suggerst" @input="Suggerst" @keyup.enter="handleSearch" type="text"
            @blur="() => search_border = false" @focus="() => search_border = true" placeholder="歌手，歌曲或专辑名">
        <div class="suggest" v-if="SuggerstData.length">
            <div v-for="(item, index) in SuggerstData" :key="index"
                @click="() => handleSearch({ keyCode: 13, target: { value: item.name } })">
                <Search style="width: 16px;color: #ccc;margin: 0 10px;" />
                <div>{{ item.name }}</div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, toRefs } from "vue"
import { useRouter } from "vue-router"
import useCounterStore from "@/stores/counter";
import { Search } from "@element-plus/icons-vue";
import { getSuggest } from "@/api/search"

const { searchInput } = toRefs(useCounterStore())
const router = useRouter()

const search_border = ref<boolean>(false)//搜索框获取焦点后显示边框
const SuggerstData = ref<any>([])


const Suggerst = (e: any) => {
    const keywords = e.target.value
    // 判断是否是中文输入法
    if (e.type === "compositionend") {
        // 获取搜索建议
        getSuggest({ keywords }).then((res: any) => {
            // 显示搜索建议
            SuggerstData.value = res.data.result.songs
        })
    }
    SuggerstData.value = []
}

//获取搜索结果，进行跳转
const handleSearch = (e: any) => {
    // 判断按下的是否是Enter键
    if (e.keyCode === 13) {
        // 获取搜索框的值
        searchInput.value = e.target.value
        // 跳转到搜索页面
        router.push({ path: '/home/search' })
        SuggerstData.value = []
    }
}

</script>

<style lang="scss" scoped>
.search {
    width: 25vw;
    height: 5vh;
    border-radius: 4px;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    position: relative;

    .suggest {
        position: absolute;
        top: 40px;
        background: rgba(0, 0, 0, 0.8);
        border-radius: 8px;
        width: 24vw;
        padding: 4px 0;

        div {
            display: flex;
            align-items: center;
            height: 6vh;
            color: #f5efef;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            div{
                width: 82%;
                font-size: 14px;
            }
        }

        div:hover {
            background: rgba(66, 64, 64, 0.5);
            cursor: pointer;
        }
    }

    input {
        width: 20vw;
        background: rgba(0, 0, 0, 0);
        border: none;
        font-size: 10px;
        outline: none;
    }
}

.search_border {
    border: 1px solid #fff;
}

span {
    color: #fff;
    margin: 0 1.2vw;
}

.avatar {
    width: 2.6vw;
    height: 2.6vw;
    cursor: pointer;

    img {
        width: 100%;
        height: 100%;
        border-radius: 50px;
    }


}
</style>